<template>
  <div class="message-history" ref="historyContainer">
    <!-- 加载更多按钮 -->
    <div v-if="hasMore && !loading" class="load-more-section">
      <button @click="$emit('loadMore')" class="load-more-btn">
        加载更多消息
      </button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-section">
      <div class="loading-spinner"></div>
      <span>加载中...</span>
    </div>

    <!-- 消息列表 -->
    <div class="messages-list">
      <div
        v-for="message in messages"
        :key="message.id"
        :class="[
          'message-item',
          { 'message-item--own': message.isOwn }
        ]"
      >
        <!-- 消息头像 -->
        <div v-if="!message.isOwn" class="message-avatar">
          <div class="avatar-placeholder">
            {{ message.senderName?.charAt(0) || '👤' }}
          </div>
        </div>

        <!-- 消息内容 -->
        <div class="message-content">
          <!-- 消息信息 -->
          <div class="message-info">
            <span v-if="!message.isOwn" class="sender-name">{{ message.senderName }}</span>
            <span class="message-time">{{ formatTime(message.timestamp) }}</span>
          </div>

          <!-- 消息气泡 -->
          <div class="message-bubble">
            <!-- 文本消息 -->
            <div v-if="message.type === 'text'" class="message-text">
              {{ message.content }}
            </div>

            <!-- 链接消息 -->
            <div v-else-if="message.type === 'link'" class="message-link">
              <div class="link-preview">
                <div class="link-title">【链接免费送】美的一级能效节能电热水器精选</div>
                <div class="link-desc">用电热水器洗澡CA35</div>
                <div class="link-url">{{ message.content.split('\n').pop() }}</div>
              </div>
            </div>

            <!-- 图片消息 -->
            <div v-else-if="message.type === 'image'" class="message-image">
              <img :src="message.content" :alt="message.content" />
            </div>

            <!-- 文件消息 -->
            <div v-else-if="message.type === 'file'" class="message-file">
              <div class="file-icon">📁</div>
              <div class="file-info">
                <div class="file-name">{{ getFileName(message.content) }}</div>
                <div class="file-size">{{ getFileSize(message.content) }}</div>
              </div>
              <button class="file-download">下载</button>
            </div>
          </div>
        </div>

        <!-- 自己的消息头像 -->
        <div v-if="message.isOwn" class="message-avatar message-avatar--own">
          <div class="avatar-placeholder">我</div>
        </div>
      </div>
    </div>

    <!-- 正在输入指示器 -->
    <div v-if="typingUsers.length > 0" class="typing-indicator">
      <div class="typing-avatar">
        <div class="avatar-placeholder">{{ typingUsers[0].charAt(0) }}</div>
      </div>
      <div class="typing-content">
        <div class="typing-dots">
          <span></span>
          <span></span>
          <span></span>
        </div>
        <div class="typing-text">{{ getTypingText() }}</div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="messages.length === 0 && !loading" class="empty-state">
      <div class="empty-icon">💬</div>
      <div class="empty-text">暂无消息记录</div>
      <div class="empty-desc">开始对话吧！</div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, watch, onMounted } from 'vue'

// Props
const props = defineProps({
  messages: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  },
  hasMore: {
    type: Boolean,
    default: false
  },
  typingUsers: {
    type: Array,
    default: () => []
  }
})

// Emits
defineEmits(['loadMore'])

// Refs
const historyContainer = ref(null)

// Methods
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  // 如果是今天
  if (diff < 24 * 60 * 60 * 1000) {
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }
  
  // 如果是昨天
  if (diff < 48 * 60 * 60 * 1000) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }
  
  // 其他日期
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

const getTypingText = () => {
  const count = props.typingUsers.length
  if (count === 1) {
    return `${props.typingUsers[0]} 正在输入...`
  } else if (count > 1) {
    return `${count} 人正在输入...`
  }
  return ''
}

const getFileName = (filePath) => {
  return filePath.split('/').pop() || '未知文件'
}

const getFileSize = (filePath) => {
  // 模拟文件大小
  return '1.2 MB'
}

const scrollToBottom = () => {
  nextTick(() => {
    if (historyContainer.value) {
      historyContainer.value.scrollTop = historyContainer.value.scrollHeight
    }
  })
}

// 监听消息变化，自动滚动到底部
watch(() => props.messages.length, () => {
  scrollToBottom()
})

// 组件挂载后滚动到底部
onMounted(() => {
  scrollToBottom()
})
</script>

<style scoped>
.message-history {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #fafafa;
}

.load-more-section {
  text-align: center;
  padding: 16px 0;
}

.load-more-btn {
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  background: #fff;
  color: #666;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.load-more-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.loading-section {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 16px 0;
  color: #666;
  font-size: 14px;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid #f0f0f0;
  border-top: 2px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message-item {
  display: flex;
  gap: 12px;
  max-width: 80%;
}

.message-item--own {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message-avatar {
  width: 32px;
  height: 32px;
  flex-shrink: 0;
}

.message-avatar--own {
  width: 32px;
  height: 32px;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f0f0;
  border-radius: 50%;
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.message-item--own .avatar-placeholder {
  background: #1890ff;
  color: white;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
  font-size: 12px;
}

.message-item--own .message-info {
  justify-content: flex-end;
}

.sender-name {
  color: #666;
  font-weight: 500;
}

.message-time {
  color: #999;
}

.message-bubble {
  background: #fff;
  border-radius: 12px;
  padding: 12px 16px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
  word-wrap: break-word;
}

.message-item--own .message-bubble {
  background: #1890ff;
  color: white;
}

.message-text {
  font-size: 14px;
  line-height: 1.4;
  white-space: pre-wrap;
}

.message-link .link-preview {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 12px;
  background: #f9f9f9;
}

.message-item--own .message-link .link-preview {
  background: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.2);
}

.link-title {
  font-weight: 500;
  margin-bottom: 4px;
  font-size: 14px;
}

.link-desc {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.message-item--own .link-desc {
  color: rgba(255, 255, 255, 0.8);
}

.link-url {
  font-size: 12px;
  color: #1890ff;
  text-decoration: none;
  word-break: break-all;
}

.message-item--own .link-url {
  color: rgba(255, 255, 255, 0.9);
}

.message-image img {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
  object-fit: cover;
}

.message-file {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px;
  background: #f5f5f5;
  border-radius: 8px;
}

.message-item--own .message-file {
  background: rgba(255, 255, 255, 0.1);
}

.file-icon {
  font-size: 24px;
}

.file-info {
  flex: 1;
}

.file-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 2px;
}

.file-size {
  font-size: 12px;
  color: #666;
}

.message-item--own .file-size {
  color: rgba(255, 255, 255, 0.8);
}

.file-download {
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: #fff;
  color: #666;
  cursor: pointer;
  font-size: 12px;
}

.message-item--own .file-download {
  border-color: rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1);
  color: white;
}

.typing-indicator {
  display: flex;
  gap: 12px;
  align-items: flex-end;
  margin-top: 8px;
}

.typing-avatar {
  width: 32px;
  height: 32px;
}

.typing-content {
  background: #fff;
  border-radius: 12px;
  padding: 12px 16px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.typing-dots {
  display: flex;
  gap: 4px;
  margin-bottom: 4px;
}

.typing-dots span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #ccc;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-dots span:nth-child(1) { animation-delay: -0.32s; }
.typing-dots span:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.typing-text {
  font-size: 12px;
  color: #666;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-text {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
}

.empty-desc {
  font-size: 14px;
}

/* 滚动条样式 */
.message-history::-webkit-scrollbar {
  width: 6px;
}

.message-history::-webkit-scrollbar-track {
  background: transparent;
}

.message-history::-webkit-scrollbar-thumb {
  background: #d9d9d9;
  border-radius: 3px;
}

.message-history::-webkit-scrollbar-thumb:hover {
  background: #bfbfbf;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .message-item {
    max-width: 90%;
  }
  
  .message-bubble {
    padding: 10px 12px;
  }
  
  .message-image img {
    max-width: 150px;
    max-height: 150px;
  }
}
</style>